package com.sjyp.cms.controller.admin;

import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.sjyp.cms.model.Column;
import com.sjyp.cms.model.Picture;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

public class PictureController extends BaseController {
    public void index() {
        int pageNumber = this.getParaToInt("pageNumber", 1);
        int pageSize = this.getParaToInt("pageSize", 10);
        String sql = "SELECT " +
                "t_picture.id," +
                "t_picture.`name`," +
                "t_picture.summary," +
                "t_picture.filePath," +
                "t_picture.orderNo," +
                "t_picture.createDate," +
                "t_picture.columnId ";
        String sqlExceptSelect = "FROM t_picture ";
        String columnId = this.getPara("columnId");
        if (null != columnId && !"0".equals(columnId) && !"null".equals(columnId)) {
            sqlExceptSelect = sqlExceptSelect + "where columnId=" + columnId;
            this.setAttr("currentColumnId", Integer.valueOf(columnId));
        }
        Page<Picture> pictures = Picture.dao.paginate(pageNumber, pageSize, sql, sqlExceptSelect);
        this.setAttr("pictures", pictures);
        this.setAttr("columns", this.findAllColumn());
        this.render("picture_list.html");
    }

    public void save() throws IOException {
        //文件处理
        UploadFile uFile =  this.getFile("file");
        String newFileName = null;
        if (null != uFile) {
            File file = uFile.getFile();
            String fileName = uFile.getFileName();
            //String absolutePath = file.getAbsolutePath();
            //String targetDir = absolutePath.substring(0,absolutePath.lastIndexOf(File.separator)+1);
            newFileName = String.valueOf(System.currentTimeMillis()) + fileName.substring(fileName.lastIndexOf("."),fileName.length());
            PropKit.use("app.properties");
            String newFilePath =  PropKit.get("uploadPath") + newFileName;
            FileUtils.moveFile(file,new File(newFilePath));
        }
        //处理属性
        Picture picture = this.getBean(Picture.class,"");
        if (null != newFileName) {
            picture.setFilePath(newFileName);
        }
        picture.setCreateDate(new Date(System.currentTimeMillis()));
        boolean isSucess = false;
        if (null == picture.getId()) {
            isSucess = picture.save();
        } else {
            //未上传图片，不删除旧图片
            if (null != newFileName) {
                picture.setFilePath(newFileName);
                this.delImg(picture.getId());
            }
            isSucess = picture.update();
        }
        //保存（或修改）后跳转至通用成功（或失败）页面
        this.setCommon("图片","picture",isSucess);
    }

    public void goSave() {
        Integer id = this.getParaToInt("id",null);
        if (null != id) {
            Picture picture = Picture.dao.findById(id);
            this.setAttr("picture", picture);
        }
        List<Column> columns = this.findAllColumn();
        this.setAttr("columns", columns);
        this.render("picture_form.html");
    }

    public void del() {
        Integer id = this.getParaToInt("id",null);
        this.delImg(id);
        boolean isDelSuccess = Picture.dao.deleteById(id);
        this.index();
    }

    /**
     * 获取所有栏目  新增图片 时，下拉框使用
     * @return
     */
    private List<Column> findAllColumn() {
        String sql = "SELECT " +
                "t_column.id," +
                "t_column.`name` " +
                "FROM t_column" ;
        return Column.dao.find(sql);
    }

    /**删除 图片 **/
    private void delImg(Integer id) {
        //先获取，并把文件删除
        Picture picture = Picture.dao.findById(id);
        String filePath = picture.getFilePath();
        if (StrKit.notBlank(filePath)) {
            PropKit.use("app.properties");
            FileUtils.deleteQuietly(new File(PropKit.get("uploadPath")+filePath));
        }
    }
}
